package co.th.bjc.md.helper;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import co.th.bjc.md.common.ConnectDB;
import co.th.bjc.md.model.RpRating;

public class RPRatingHelper {
	
	private static Logger _log = Logger.getLogger(RPRatingHelper.class);
	
	public List<RpRating> findAllRPRating() throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<RpRating> listRpRating = new ArrayList<RpRating>(0);
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM rp_rating ";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			
			rs = stmt.executeQuery();
			while (rs.next()){
				listRpRating.add(this.setRpRating(rs));
			}
		}catch(Exception ex){
			_log.error("findAllRPRating --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return listRpRating;
	}
	
	public RpRating findRPRatingByRPCode(BigDecimal rpCode) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		RpRating rp = null;
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM rp_rating WHERE rp_code = ?";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setBigDecimal(1, rpCode);
			
			rs = stmt.executeQuery();
			while (rs.next()){
				rp = this.setRpRating(rs);
			}
		}catch(Exception ex){
			_log.error("findRPRatingByRPCode --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return rp;
	}
	
	private RpRating setRpRating(ResultSet rs) throws Exception{
		RpRating rp = new RpRating();
		rp.setRpCode(rs.getBigDecimal("rp_code"));
		rp.setRpName(rs.getString("rp_name"));
		rp.setCreateBy(rs.getString("create_by"));
		rp.setCreateDate(rs.getDate("create_date"));
		rp.setUpdateBy(rs.getString("update_by"));
		rp.setUpdateDate(rs.getDate("update_date"));
		return rp;
	}
}
